<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="部门名称"></el-input>
				</el-form-item>
        <el-form-item label="部门状态">
          <el-select v-model="query.state" placeholder="部门状态" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="initPage">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="80">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="140" sortable>
			</el-table-column>
      <el-table-column prop="sn" label="部门编号" width="140" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="180">
        <template slot-scope="scope">

              <el-tag size="medium" v-if="scope.row.state==0" type="danger">禁用</el-tag>
              <el-tag size="medium" v-if="scope.row.state==1">启用</el-tag>

        </template>
      </el-table-column>

			<el-table-column prop="parent.name" label="上级部门" width="120" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination>-->
      <el-pagination
          style="float:right;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[5,10,20]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total=pagination.total>
      </el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="编号" prop="sn">
					<el-input v-model="saveForm.sn" ></el-input>
				</el-form-item>
        <el-form-item label="管理员" prop="managerId">
          <template>
            <el-select v-model="saveForm.managerId" placeholder="请选择">
              <el-option
                  v-for="item in emps"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
            <el-cascader
                v-model="saveForm.parentId"
                :options="tree"
                :props="{
                          checkStrictly:true,
                          label:'name',
                          value:'id'
                       }"
                ></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="addForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="addForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					name: ''
				},
				depts: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列
        query:{
          keyword:'',
          state:'',
        },
        pagination:{
          currentPage:1,
          pageSize:10,
          total:0,
          keyword:'',
          state:'',
        },

				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				saveForm: {
					id: null,
					name: '',
					state: 0,
					sn: null,
          managerId: '',
					parentId: ''
				},
        //管理员信息
        emps:[],
        addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
        //部门级树
        tree:[],
				//新增界面数据
				addForm: {
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				}

			}
		},
		methods: {
			handleCurrentChange(val) {
				this.pagination.currentPage=val
				this.getDepts();
			},
      handleSizeChange(val){
        this.pagination.pageSize=val
        this.getDepts()
      },
      //查询和删除时初始化分页信息
      initPage(){
        this.pagination.keyword=this.query.keyword
        this.pagination.state=this.query.state
        this.pagination.currentPage=1
        this.getDepts()
      },
			//获取部门列表
			getDepts() {
				let para = {
					page: this.page,
					name: this.filters.name
				};
				this.listLoading = true;
				//NProgress.start();
        this.$http.post("/department/list",this.pagination).then(res=>{
          this.depts=res.data.data
          this.pagination.total=res.data.total
          this.listLoading = false;
        })
			},
      //获取管理员列表
      getEmps(){
        this.$http.get("/emps").then(res=>{
          if (res.data.flag){
            /*this.$message({
              message:res.data.msg,
              type:'success'
            })*/
            this.emps=res.data.data
          }else {
            this.$message({
              message:res.data.msg,
              type:'warning'
          }
        )}
      })},
      //获取部门级树
      getTree(){
        console.log(1)
        this.$http.post("/department/tree").then(res=>{
          if (res.data.flag){
            this.tree=res.data.data
          }
        })
      },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          this.$http.delete("/department/"+row.id).then(res=>{

            if (res.data.flag){
              this.$message({
                message:res.data.msg,
                type:'success'
              })
            }else {
              this.$message({
                message:res.data.msg,
                type:'warning'
              })
            }
            this.listLoading = false;
            this.initPage()
          })
					/*this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepts();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        if (this.$refs['saveForm']){
          this.$refs['saveForm'].resetFields();
        }
				this.saveFormVisible = true;

				this.saveForm = Object.assign({}, row);
        console.log(this.saveForm)
			},
			//显示新增界面
			handleAdd: function () {
        if (this.$refs['saveForm']){
          this.$refs['saveForm'].resetFields();
        }

				this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          name: '',
          state: 0,
          sn: null,
          managerId: '',
          parentId: ''
				};
			},
			//编辑
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;

              if (this.saveForm.parentId!==null&&typeof(this.saveForm.parentId)=='object'){
                this.saveForm.parentId=this.saveForm.parentId[this.saveForm.parentId.length-1]
              }

              this.$http.put("/department",this.saveForm).then(res=>{

                if (res.data.flag){
                  this.$message({
                    message:res.data.msg,
                    type:'success'
                  })
                }else {
                  this.$message({
                    message:res.data.msg,
                    type:'warning'
                  })
                }
                this.saveLoading = false;
                this.saveFormVisible = false;
                this.$refs['saveForm'].resetFields();
                this.getDepts()
              })

						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        console.log(ids)
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          //开启忙等
          this.listLoading = true;
          this.$http.patch("/department",ids).then(res=>{
            console.log(res)
            if (res.data.flag){
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              this.getDepts()
            }else {
              this.$message({
                message: res.data.msg,
                type: 'warning'
              });
            }
            this.listLoading=false

          })
        }).catch(() => {
        });
      }
		},
		mounted() {
			this.getDepts();
      this.getEmps();
      this.getTree();
		}
	}

</script>

<style scoped>

</style>